const { JSDOM } = require("jsdom");

const ShopCart = ({ res, response }) => {
  res.setHeader("Content-Type", "application/json");
  try {
    const dom = new JSDOM(response);
    const document = dom.window.document;
    const promotionList = [];

    const domList = [
      ...document.querySelector(".Promotions").querySelectorAll("dd"),
    ];

    domList.forEach((dd) => {
      const value = dd.querySelector("input").value;

      promotionList.push({
        value,
        label: dd.textContent,
      });
    });

    const dom2 = document.querySelector(".billing").querySelector(".biR");
    const dom3 = dom2.querySelectorAll("em");
    // tabs1
    const shoppingList = [];
    const domList2 = [
      ...document.querySelector(".tabs1 tbody").querySelectorAll("tr"),
    ];
    domList2.forEach((tr) => {
      const [td1, td2, td3, td4, td5] = [...tr.querySelectorAll("td")];
      const pic = td1.querySelector("img").src;
      const name = td1.querySelector(".name").textContent;
      const price = td2.querySelector("em").textContent;
      const num = td3.querySelector("input").value;
      const amount = td4.querySelector("em").textContent;
      const id = td5.innerHTML.match(/\('(.*?)'\)/)[1];

      const isDelete = document.querySelector(".tableA p")?.innerHTML;

      shoppingList.push({
        id,
        pic,
        name,
        price,
        num,
        amount,
      });
    });

    return JSON.stringify({
      data: {
        shoppingList,
        promotionList,
        billingInformation: dom2.innerHTML,
        isDelete: true,
        totalPrice: dom3[dom3.length - 1].innerHTML,
      },
      success: true,
    });
  } catch (error) {
    return JSON.stringify({
      success: false,
    });
  }
};

module.exports = {
  ShopCart,
};
